package com.teradata.io.bio;


import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * @Project: cmcchq
 * @Description:
 * @Version 1.0
 * @Throws :
 * @Author: <li>2019/6/14 lyndon Create 1.0
 * @Copyright (c)2019-2019 版权所有
 * @Modified By:
 */

@Slf4j
public class ServerHandler implements Runnable {

    private Socket socket;

    public ServerHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        BufferedReader in = null;
        PrintWriter out = null;

        try {
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);
            String expression;
            String result;

            while (true) {
                if ((expression = in.readLine()) == null) {
                    break;
                }
                //System.out.println("服务端收到消息:" + expression);
                log.info("服务端收到消息:{}", expression);
                result = Calculator.cal(expression);
                out.println(result);
            }

        } catch (IOException e) {
            e.printStackTrace();
            //System.out.println(e.getLocalizedMessage());
            log.error(e.getLocalizedMessage());
        } finally {
            if (in != null) {
                try {
                    in.close();
                    in = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null) {
                out.close();
                out = null;
            }

            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                socket = null;
            }
        }


    }
}
